package net.uman.service;

import java.util.Set;

import net.uman.entity.User;
import net.uman.framework.modules.utils.MessageHelper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.google.common.collect.Sets;

/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数.
 * @author calvin
 */
public class UserDetailsServiceImpl implements UserDetailsService {

	private UserManager userManager;
	MessageHelper properties;
	/**
	 * 获取用户Details信息的回调函数.
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
	    StringBuffer msg = new StringBuffer(200);
	    
		User user = userManager.getUserByLoginName(username);
		if(user == null){
			msg.append(MessageHelper.getMessagePro("auditlog.systemmanagement.login.fail", new Object[]{username}));
			user = new User();
		    user.setName(username);
			throw new UsernameNotFoundException("用户" + username + "不存在!");
		}
		
		Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user);

		//-- mini-web示例中无以下属性, 暂时全部设为true. --//
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		UserDetails userdetails = new org.springframework.security.core.userdetails.User(user.getLoginName(), user
				.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);

		return userdetails;
	}

	/**
	 * 获得用户所有角色的权限集合.
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities(User user) {
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		authSet.add(new GrantedAuthorityImpl("ddd"));
//		for (Role role : user.getRoleList()) {
//			for (Authority authority : role.getAuthorityList()) {
//				authSet.add(new GrantedAuthorityImpl(authority.getPrefixedName()));
//			}
//		}
		return authSet;
	}

	@Autowired
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
}
